using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using Clanta.Core.Domain;
using Clanta.Web.Controls;
using Clanta.Core.DataInterfaces;
using System.Collections.Generic;
using System.ComponentModel;
using NHibernate;
using Clanta.Web.ReportDatamodels;
using Clanta.Data;
using System.Globalization;

namespace Clanta.Web.User
{

    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RadioButtonListGroupBy.SelectedIndex = 0;
                RadioButtonListTotalerGns.SelectedIndex = 0;

                if (!string.IsNullOrEmpty(Request.QueryString.Get("conferenceId")))
                {
                    ConferenceDropDownList.SelectedValue = Request.QueryString.Get("conferenceId");
                }
            }
            ConferenceDropDownList.DataBound += new EventHandler(ConferenceDropDownList_DataBound);
        }

        void ConferenceDropDownList_DataBound(object sender, EventArgs e)
        {
            HentDataTilKriterier();
        }

        protected void PresentationGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Presentation presentation = (Presentation)e.Row.DataItem;

                Label trackNameLabel = (Label)e.Row.FindControl("TrackNameLabel");
                trackNameLabel.Text = "";
                if (presentation.Track != null)
                {
                    trackNameLabel.Text = presentation.Track.Name;
                }

                Label speakersLabel = (Label)e.Row.FindControl("SpeakersLabel");
                string[] speakerNames =
                    new List<Speaker>(presentation.Speakers).ConvertAll(
                        new Converter<Speaker, string>(delegate(Speaker speaker) { return speaker.Name; })).ToArray();
                speakersLabel.Text = string.Join(", ", speakerNames);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            LabelIngenResultater.Visible = false;
            ////////////////////////
            DateTime tempOut = new DateTime();
            DateTime.TryParse(DropDownListDay.SelectedValue, out tempOut);

            List<Presentation> presentations = new GeneralStatisticsInformation(Server.MapPath(@"~/Config/ClantaNHibernate.config")).GetPresentationsByCriteria(DropDownListSpeakers.SelectedValue, DropDownListTracks.SelectedValue, DropDownListDay.SelectedValue, long.Parse(ConferenceDropDownList.SelectedValue), tempOut);
            SimpleStatDataSet data = new SimpleStatDataSet();
            string grupperEfter = null;

            foreach (Presentation presentation in presentations)
            {
                int red = presentation.Red != null ? (int)presentation.Red : 0;
                int green = presentation.Green != null ? (int)presentation.Green : 0;
                int yellow = presentation.Yellow != null ? (int)presentation.Yellow : 0;
                int total = presentation.NoOfParticipants != null ? (int)presentation.NoOfParticipants : 0;

                if (red != 0 || green != 0 || yellow != 0 || total != 0)
                {
                    if (RadioButtonListGroupBy.SelectedValue == "Date") grupperEfter = ((DateTime)presentation.PresentationStart).ToShortDateString();
                    if (RadioButtonListGroupBy.SelectedValue == "Track") grupperEfter = presentation.Track != null ? presentation.Track.Name : "Keynote";
                    if (RadioButtonListGroupBy.SelectedValue == "Presentation") grupperEfter = presentation.Name;
                    if (RadioButtonListGroupBy.SelectedValue == "Speaker")
                    {
                        foreach (Speaker speaker in presentation.Speakers)
                        {
                            if (DropDownListSpeakers.SelectedValue == "-1" || DropDownListSpeakers.SelectedValue == speaker.Id.ToString())
                            {
                                data.Data.AddDataRow(red, yellow, green, speaker.Name, total, presentation.Name + ", " + speaker.Name);
                            }
                        }
                    }
                    else
                    {
                        data.Data.AddDataRow(red, yellow, green, grupperEfter, total, presentation.Name + ", " + presentation.Speakers.ToString());
                    }
                }
            }
            if (data.Data.Rows.Count > 0)
            {
                if (RadioButtonListTotalerGns.SelectedValue == "Totaler")
                {
                    ClantaSimpleReport_sum report = new ClantaSimpleReport_sum();
                    report.SetDataSource(data);
                    string reportId = System.Guid.NewGuid().ToString();
                    string uniqueFileName = String.Format("ClantaReport-{0}.rpt", reportId);
                    string reportFileAbsPath = null;
                    try
                    {
                        string reportsPath = this.Server.MapPath("Reports");
                        if (!System.IO.Directory.Exists(reportsPath))
                        {
                            System.IO.Directory.CreateDirectory(reportsPath);
                        }
                        reportFileAbsPath = System.IO.Path.Combine(reportsPath, uniqueFileName);
                        report.SaveAs(reportFileAbsPath, true);
                        report.Dispose();
                    }
                    catch
                    {
                    }

                    if (reportFileAbsPath != null)
                    {
                        Response.Redirect(String.Format("ReportView.aspx?id={0}&conferenceID={1}", reportId, ConferenceDropDownList.SelectedValue));
                    }
                }
                else if (RadioButtonListTotalerGns.SelectedValue == "Gennemsnit")
                {
                    ClantaSimpleReport_average report = new ClantaSimpleReport_average();
                    report.SetDataSource(data);
                    string reportId = System.Guid.NewGuid().ToString();
                    string uniqueFileName = String.Format("ClantaReport-{0}.rpt", reportId);
                    string reportFileAbsPath = null;
                    try
                    {
                        string reportsPath = this.Server.MapPath("Reports");
                        if (!System.IO.Directory.Exists(reportsPath))
                        {
                            System.IO.Directory.CreateDirectory(reportsPath);
                        }
                        reportFileAbsPath = System.IO.Path.Combine(reportsPath, uniqueFileName);
                        report.SaveAs(reportFileAbsPath, true);
                    }
                    catch
                    {
                    }

                    if (reportFileAbsPath != null)
                    {
                        Response.Redirect(String.Format("ReportView.aspx?id={0}&conferenceID={1}", reportId, ConferenceDropDownList.SelectedValue));
                    }
                }
                else if (RadioButtonListTotalerGns.SelectedValue == "Procent")
                {
                    SimpleStatDataSet dataSomProcent = BeregnProcentvisFordeling(data);
                    ClantaSimpleReport_sum report = new ClantaSimpleReport_sum();
                    report.SetDataSource(dataSomProcent);
                    string reportId = System.Guid.NewGuid().ToString();
                    string uniqueFileName = String.Format("ClantaReport-{0}.rpt", reportId);
                    string reportFileAbsPath = null;
                    try
                    {
                        string reportsPath = this.Server.MapPath("Reports");
                        if (!System.IO.Directory.Exists(reportsPath))
                        {
                            System.IO.Directory.CreateDirectory(reportsPath);
                        }
                        reportFileAbsPath = System.IO.Path.Combine(reportsPath, uniqueFileName);
                        report.SaveAs(reportFileAbsPath, true);
                    }
                    catch
                    {
                    }

                    if (reportFileAbsPath != null)
                    {
                        Response.Redirect(String.Format("ReportView.aspx?id={0}&conferenceID={1}", reportId, ConferenceDropDownList.SelectedValue));
                    }
                }
            }
            else
            {
                LabelIngenResultater.Visible = true;
            }
        }

        private SimpleStatDataSet BeregnProcentvisFordeling(SimpleStatDataSet data)
        {
            Dictionary<string, string> brugteNavne = new Dictionary<string, string>();
            SimpleStatDataSet nytDataSet = new SimpleStatDataSet();
            foreach (SimpleStatDataSet.DataRow row in data.Data.Rows)
            {

                if (!brugteNavne.ContainsKey(row.GroupingElement))
                {
                    brugteNavne.Add(row.GroupingElement, row.GroupingElement);

                    foreach (SimpleStatDataSet.DataRow rowTemp in data.Data.Rows)
                    {

                        if (row != rowTemp && row.GroupingElement == rowTemp.GroupingElement)
                        {
                            row.Green += rowTemp.Green;
                            row.Red += rowTemp.Red;
                            row.Yellow += rowTemp.Yellow;
                        }

                    }
                    double total = row.Green + row.Red + row.Yellow;
                    row.Green = (int)(((double)row.Green / total) * 100);
                    row.Red = (int)(((double)row.Red / total) * 100);
                    row.Yellow = (int)(((double)row.Yellow / total) * 100);
                    row.NoOfParticipants = 100;
                    
                    nytDataSet.Data.AddDataRow(row.Red, row.Yellow, row.Green, row.GroupingElement, row.NoOfParticipants, row.Presentation);
                }
            }
            
            return nytDataSet;
        }

        protected void ConferenceDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            HentDataTilKriterier();
        }

        void HentDataTilKriterier()
        {
            GeneralStatisticsInformation gsi = new GeneralStatisticsInformation(Server.MapPath(@"~/Config/ClantaNHibernate.config"));
            DropDownListSpeakers.DataSource = gsi.GetSpeakersByConferenceId(long.Parse(ConferenceDropDownList.SelectedValue));
            DropDownListSpeakers.DataTextField = "Text";
            DropDownListSpeakers.DataValueField = "Id";
            DropDownListSpeakers.AppendDataBoundItems = false;
            DropDownListSpeakers.DataBind();

            DropDownListTracks.DataSource = gsi.GetTracksByConferenceId(long.Parse(ConferenceDropDownList.SelectedValue));
            DropDownListTracks.DataTextField = "Text";
            DropDownListTracks.DataValueField = "Id";
            DropDownListTracks.AppendDataBoundItems = false;
            DropDownListTracks.DataBind();

            DropDownListDay.DataSource = gsi.GetDaysByConferenceId(long.Parse(ConferenceDropDownList.SelectedValue));
            DropDownListDay.DataTextField = "Text";
            DropDownListDay.DataValueField = "Id";
            DropDownListDay.AppendDataBoundItems = false;
            DropDownListDay.DataBind();
        }

        #region Event Handlers

        protected void ConferenceObjectDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = new ConferenceDataObject(Server.MapPath(@"~/Config/ClantaNHibernate.config"));
        }

        protected void PresentationsByConferenceIdObjectDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = new PresentationDataObject(Server.MapPath(@"~/Config/ClantaNHibernate.config"));
        }

        #endregion
    }

    public abstract class AbstractDataObject
    {
        //public AbstractDataObject() { }
        public AbstractDataObject(string sessionFactoryConfigPath)
        {
            daoFactory = new Clanta.Data.NHibernateDaoFactory(sessionFactoryConfigPath);
            this.sessionFactoryConfigPath = sessionFactoryConfigPath;
        }

        /// <summary>
        /// Exposes accessor for the <see cref="IDaoFactory" /> used by all user controls.
        /// </summary>
        protected IDaoFactory DaoFactory
        {
            get
            {
                return daoFactory;
                //return (IDaoFactory)CustomHttpApplication.WindsorContainer[typeof(IDaoFactory)];
            }
        }

        private IDaoFactory daoFactory;
        protected string sessionFactoryConfigPath;
    }

    [DataObject]
    public class ConferenceDataObject : AbstractDataObject
    {
        //public ConferenceDataObject() { }

        public ConferenceDataObject(string sessionConfigFactoryPath)
            : base(sessionConfigFactoryPath)
        {
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public List<Conference> GetConferencesForCustomer()
        {
            return DaoFactory.ConferenceDao.GetConferencesByCustomerId(1);
        }
    }

    [DataObject]
    public class PresentationDataObject : AbstractDataObject
    {
        //public PresentationDataObject() { }

        public PresentationDataObject(string sessionConfigFactoryPath)
            : base(sessionConfigFactoryPath)
        {
        }

        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public IList<Presentation> GetPresentationsByConferenceId(long conferenceId)
        {
            return DaoFactory.PresentationDao.GetPresentationsByConferenceId(conferenceId);
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public IList<Presentation> GetPresentationsByConferenceId(long conferenceId, string sortParameter)
        {
            List<Presentation> presentations = new List<Presentation>(DaoFactory.PresentationDao.GetPresentationsByConferenceId(conferenceId));
            return presentations;
        }

        [DataObjectMethod(DataObjectMethodType.Update, true)]
        public void UpdateMeasurementForPresentation(int? green, int? yellow, int? red, int? noofparticipants, long original_id, long original_version)
        {
            ProjectBase.Data.NHibernateSessionManager.Instance.BeginTransactionOn(sessionFactoryConfigPath);

            Presentation presentation = DaoFactory.PresentationDao.GetById(original_id, true);
            if (presentation.Version != original_version)
            {
                throw new StaleObjectStateException(typeof(Presentation), original_id);
                //"Presentation was modified by someone else");
            }

            presentation.Green = green;
            presentation.Yellow = yellow;
            presentation.Red = red;
            presentation.NoOfParticipants = noofparticipants;

            DaoFactory.PresentationDao.CommitChanges();
        }

    }

}
